package com.agent.vpsserver.common.utils.stream;

import cn.hutool.core.codec.Base64Encoder;
import com.agent.vpsserver.common.utils.common.StringUtils;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * description
 *
 * @author <a href="mailto:ludezh@dingtalk.com"> ludezh </a>
 * @version 1.0.0   2019/10/18,10:29
 * @since 1.0.0     2019/10/18,10:29
 */
public class ImageUtils {
    private static final String IMAGE_SUFFIX = ".png";
    public static final String IMAGE_SUFFIX_TYPE = "png";


    /**
     * 图片合成 生成base64流
     *
     * @param [posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight]
     * @return java.lang.String
     * @author ludezh
     * @date 2019/10/18 11:13
     * @version 1.0.0
     */
    public static String drawImage2Base64(String posterImgUrl, String tempQrCodeImgUrl, String headImgUrl, String nameText,
                                          String cqText, Integer bWith, Integer bHeight) throws IOException {
        ByteArrayOutputStream bs = drawImage2Stream(posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight);
        byte[] bytes = bs.toByteArray();
        return Base64Encoder.encode(bytes);
    }

    /**
     * 图片合成 生成流
     *
     * @param [posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight]
     * @return java.io.ByteArrayOutputStream
     * @author ludezh
     * @date 2019/10/18 11:13
     * @version 1.0.0
     */
    public static ByteArrayOutputStream drawImage2Stream(String posterImgUrl, String tempQrCodeImgUrl, String headImgUrl, String nameText,
                                                         String cqText, Integer bWith, Integer bHeight) throws IOException {
        BufferedImage bufferedImage = drawImage(posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imgOut = ImageIO.createImageOutputStream(bs);
        ImageIO.write(bufferedImage, IMAGE_SUFFIX_TYPE, imgOut);
        return bs;
    }

    /**
     * 图片合成 保存在本地   filePath如E:\demo2.png
     *
     * @param [posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight, filePath]
     * @return void
     * @author ludezh
     * @date 2019/10/18 11:12
     * @version 1.0.0
     */
    public static void drawImage2LocalPic(String posterImgUrl, String tempQrCodeImgUrl, String headImgUrl, String nameText,
                                          String cqText, Integer bWith, Integer bHeight, String filePath) throws IOException {
        BufferedImage bs = drawImage(posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight);
        ImageIO.write(bs, IMAGE_SUFFIX_TYPE, new File(filePath));
    }

    /**
     * 根据图片url合成一张图
     *
     * @param posterImgUrl     海报
     * @param tempQrCodeImgUrl 临时二维码
     * @param headImgUrl       头像
     * @param nameText         昵称
     * @param cqText           二维码文字
     * @return java.lang.String
     * @author ludezh
     * @date 2019/10/18 10:46
     * @version 1.0.0
     */
    public static BufferedImage drawImage(String posterImgUrl, String tempQrCodeImgUrl, String headImgUrl, String nameText,
                                          String cqText, Integer bWith, Integer bHeight) throws IOException {

        int width = 620;
        int height = 1004;
        if (null != bWith) {
            width = bWith;
        }
        if (null != bHeight) {
            height = bHeight;
        }
        BufferedImage bgBufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// RGB形式}}
        Graphics2D bgBufImageGraphics = bgBufImage.createGraphics();
        bgBufImageGraphics.setBackground(Color.WHITE);// 设置背景色
        bgBufImageGraphics.clearRect(0, 0, width, height);// 通过使用当前绘图表面的背景色进行填充来清除指定的矩形。

        // bgBufImageGraphics.setBackground(new Color(255,255,255));
        bgBufImageGraphics.setPaint(Color.black);// 设置画笔,设置Paint属性
        Font font = new Font("微软雅黑", Font.PLAIN, 18);
        bgBufImageGraphics.setFont(font);
        // 抗锯齿
        bgBufImageGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 计算文字长度，计算居中的x点坐标
        FontMetrics fm = bgBufImageGraphics.getFontMetrics(font);
        int textWidth = fm.stringWidth(nameText);
        int widthX = (width - textWidth) / 2;
        if (StringUtils.isNotBlank(nameText)) {
            widthX = 120;
            // 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
            bgBufImageGraphics.drawString(nameText, widthX, 958);
        }
        if (StringUtils.isNotBlank(cqText)) {
            // 计算文字长度，计算居中的x点坐标
            // int widthX = (width - textWidth) / 2;
            int cqCodeWidthX = 412;
            // 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
            bgBufImageGraphics.drawString(cqText, cqCodeWidthX, 958);
        }
        // BufferedImage posterBufImage = ImageIO.read(new URL(posterImgUrl));
        // //直接使用图片做背景，自定义背景使用上面方式
        // Graphics2D posterBufImageGraphics = posterBufImage.createGraphics();

        BufferedImage posterBufImage = ImageIO.read(new URL(posterImgUrl));
        BufferedImage qrCodeImage = ImageIO.read(new URL(tempQrCodeImgUrl));
        BufferedImage headImage = ImageIO.read(new URL(headImgUrl));

        // 设置圆形头像
        BufferedImage roundHeadImg = new BufferedImage(headImage.getWidth(), headImage.getHeight(),
                BufferedImage.TYPE_INT_RGB);

        Graphics2D roundHeadGraphics = roundHeadImg.createGraphics();
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, roundHeadImg.getWidth(), roundHeadImg.getHeight());
        roundHeadGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        roundHeadImg = roundHeadGraphics.getDeviceConfiguration().createCompatibleImage(headImage.getWidth(),
                headImage.getHeight(), Transparency.TRANSLUCENT);
        roundHeadGraphics = roundHeadImg.createGraphics();
        // 使用 setRenderingHint 设置抗锯齿
        roundHeadGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        roundHeadGraphics.setClip(shape);
        roundHeadGraphics.drawImage(headImage, 0, 0, null);
        roundHeadGraphics.dispose();

        bgBufImageGraphics.drawImage(qrCodeImage, 444, 848, 72, 72, null);
        bgBufImageGraphics.drawImage(roundHeadImg, 32, 876, 80, 80, null);
        bgBufImageGraphics.drawImage(posterBufImage, 0, 0, 620, 826, null);
        bgBufImageGraphics.dispose();

        return bgBufImage;
    }

    /**
     * 图片合成 生成字节流
     *
     * @param [posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight]
     * @return java.lang.String
     * @author ludezh
     * @date 2019/10/18 11:13
     * @version 1.0.0
     */
    public static ByteArrayOutputStream drawImageQr2Stream(String posterPath, String qrCodeData, String logoPath, Integer qrSize, Integer width, Integer height) throws Exception {
        BufferedImage bufferedImage = drawImageQr4Path(posterPath, qrCodeData, logoPath, qrSize, width, height);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imgOut = ImageIO.createImageOutputStream(bs);
        ImageIO.write(bufferedImage, IMAGE_SUFFIX_TYPE, imgOut);
        return bs;
    }

    /**
     * 图片合成 生成base64流
     *
     * @param [posterImgUrl, tempQrCodeImgUrl, headImgUrl, nameText, cqText, bWith, bHeight]
     * @return java.lang.String
     * @author ludezh
     * @date 2019/10/18 11:13
     * @version 1.0.0
     */
    public static String drawImageQr2Base64(String posterPath, String qrCodeData, String logoPath, Integer qrSize, Integer width, Integer height) throws Exception {
        BufferedImage bufferedImage = drawImageQr4Path(posterPath, qrCodeData, logoPath, qrSize, width, height);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imgOut = ImageIO.createImageOutputStream(bs);
        ImageIO.write(bufferedImage, IMAGE_SUFFIX_TYPE, imgOut);
        byte[] bytes = bs.toByteArray();
        bs.close();
        return Base64Encoder.encode(bytes);
    }

    /**
     * 图片本地地址 + 生成二维码合成
     *
     * @param posterPath 海报
     * @param qrCodeData 二维码数据
     * @param logoPath   logo
     * @param qrSize     二维码尺寸
     * @param width      二维码x轴距离
     * @param height     二维码y轴距离
     * @return java.lang.String
     * @author ludezh
     * @date 2019/10/18 10:46
     * @version 1.0.0
     */
    public static BufferedImage drawImageQr4Path(String posterPath, String qrCodeData, String logoPath, Integer qrSize, Integer width, Integer height) throws Exception {
        // 海报
        InputStream posterInput = QrCodeUtils.getResourceAsStream(posterPath);
        BufferedImage posterBufImage = ImageIO.read(posterInput);
//        int width = posterBufImage.getWidth(null);
//        int height = posterBufImage.getHeight(null);

        // RGB形式 画布
//        BufferedImage bgBufImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 以海报当画布
        Graphics2D bgBufImageGraphics = posterBufImage.createGraphics();
        // 创建二维码
        BufferedImage qrCodeImage = QrCodeUtils.createImage(qrCodeData, logoPath, true, qrSize);
//        int width1 = qrCodeImage.getWidth();
//        int height1 = qrCodeImage.getHeight();
        bgBufImageGraphics.drawImage(qrCodeImage, width, height, qrSize, qrSize, null);
//        Shape shape = new RoundRectangle2D.Float(width, height, width1, width1, 6, 6);
//        bgBufImageGraphics.setStroke(new BasicStroke(3f));
//        bgBufImageGraphics.draw(shape);
        bgBufImageGraphics.dispose();
        return posterBufImage;
    }

//    public static void main(String[] args) throws Exception {
//        BufferedImage bufferedImage = drawImageQr4Path(
//                "E:\\\\rp_poster.png",
////                "https://s.click.taobao.com/t?e=m%3D2%26s%3DldInG0DDWfsoTv%2BIBSoIuymOywG",
//                "https://s.click.taobao.com/t?e=m%3D2%26s%3DldInG0%2B0mQJw4vFB6t2Z2iperVdZeJviyK8Cckff7TVRAdhuF14FMVnCnBuzGCJt1aH1Hk3GeOjLU5X4B%2BcNZNLBaBuLMFEyLPABrCxUWyaaySCDrfVZvyPDB%2BMCD7Erjnvs3ugiPp3iCpeCUkeJcznpmhTObRx2eAkx3bKOzfs7g3kLGWv47YAdhZVHU%2FI%2FnLONVA18r1Je8QeBpZcnhwzM%2F3DDWfsoTv%2BIBSoIuymOywGtw1KzNma%2BrI7nTFh0dAbgUPAw0dxqpNqFAokvy%2FAjgEQY9ODt5pB1PT3DQXvliXQvfFtgXgGD4Qvv4GhPM7kxpdONUAK2ZesAkYM2UrHfv3%2BBYcPW%2FknKiHyNnnywB5MhWbQYoeTR%2Fh3p6vFjiSLq71w5u%2BUJ3widuiY%2FFWC7mVw243jEbA724fELe4f8zFlMerWS1ckKdJsOW0%2F1L4Q%2BMddJMmVgUXTX%2FcVpYRwVqRgKrcV2tuG05VoHAYg%3D&pvid=24797981&union_lens=lensId:0b582d96_0c5e_16dd7a98e77_5269",
//                "E:\\\\taobao_logo.png", 265, 240, 834);
//        ImageIO.write(bufferedImage, "png", new File("E:\\demo5.jpg"));
//    }
//    public static void main(String[] args) {
//        try {
//            String backgroundImageUrl = "http://diaosaas-prod.oss-cn-shenzhen.aliyuncs.com/education/155547979572510070.jpg";
//            // 二维码
//            String qrCodeImageUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1553504957130&di=02fae20a5c0f885d52299b2b1d682c86&imgtype=0&src=http%3A%2F%2Fimg.atobo.com%2FProductImg%2FEWM%2FUWeb%2F3%2F2%2F1%2F3%2F061%2F3213061%2F1.gif";
//            // 头像
//            // String headUrl =
//            // "http://pic.51yuansu.com/pic3/cover/00/63/25/589bdedf5475d_610.jpg";
//            String headUrl = "http://thirdwx.qlogo.cn/mmopen/vi_32/ZW8dgKbUicrCdotRItMTpAaxibAwj6nVMJvQoGLyKbaRvah93dXWrENSoum20dKicnJqd2xh1U4NhmC41L7q2Gwqg/132";
//            String nameText = "古月争取";
//            String cqText = "扫一扫，为我加油！";
//            ImageUtils.drawImage2LocalPic(backgroundImageUrl, qrCodeImageUrl, headUrl, nameText, cqText, null, null, "E:\\demo2.png");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 提取html 标签中的src url
     * @return
     */
    public static List<String> extractImageUrl(String htmlStr){
        if(StringUtils.isBlank(htmlStr)){
            return null;
        }
        List<String> list = new ArrayList<>();
        Matcher matcher = Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(htmlStr);
        while(matcher.find()){
            list.add(matcher.group(1));
        }
        if(list!=null&&list.size()>0&&list.get(0).endsWith("spaceball.gif")){
            return list.subList(1,list.size());
        }
        return list;
    }


}
